package com.enation.app.javashop.consumer.shop.trade.consumer;

import com.dag.eagleshop.core.account.model.dto.payment.PaymentRecordDTO;
import com.dag.eagleshop.core.account.model.enums.TradeChannelEnum;
import com.dag.eagleshop.core.account.model.enums.TradeStatusEnum;
import com.dag.eagleshop.core.account.model.enums.TradeSubjectEnum;
import com.dag.eagleshop.core.account.service.AccountManager;
import com.enation.app.javashop.consumer.core.event.OrderStatusChangeEvent;
import com.enation.app.javashop.core.aftersale.model.enums.AccountTypeEnum;
import com.enation.app.javashop.core.base.message.OrderStatusChangeMsg;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.orderbill.utils.SettleUtils;
import com.enation.app.javashop.core.payment.model.dos.PaymentBillDO;
import com.enation.app.javashop.core.payment.model.dos.PaymentMethodDO;
import com.enation.app.javashop.core.payment.model.enums.PaymentPluginEnum;
import com.enation.app.javashop.core.payment.service.PaymentBillManager;
import com.enation.app.javashop.core.payment.service.PaymentMethodManager;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.core.trade.order.model.dos.PayLog;
import com.enation.app.javashop.core.trade.order.model.enums.OrderStatusEnum;
import com.enation.app.javashop.core.trade.order.model.enums.PayStatusEnum;
import com.enation.app.javashop.core.trade.order.model.vo.OrderSkuVO;
import com.enation.app.javashop.core.trade.order.service.PayLogManager;
import com.enation.app.javashop.core.trade.order.service.TradeSnCreator;
import com.enation.app.javashop.core.trade.sdk.model.OrderSkuDTO;
import com.enation.app.javashop.framework.util.CurrencyUtil;
import com.enation.app.javashop.framework.util.JsonUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 订单支付后，修改付款单
 *
 * @author Snow create in 2018/7/23
 * @version v2.0
 * @since v7.0.0
 */
@Component
public class OrderPayLogConsumer implements OrderStatusChangeEvent {

    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private PayLogManager payLogManager;
    @Autowired
    private PaymentMethodManager paymentMethodManager;
    @Autowired
    private AccountManager accountManager;
    @Autowired
    private MemberManager memberManager;
    @Autowired
    private PaymentBillManager paymentBillManager;
    @Autowired
    private TradeSnCreator tradeSnCreator;

    @Override
    public void orderChange(OrderStatusChangeMsg orderMessage) {

        //订单已付款
        if(orderMessage.getNewStatus().name().equals(OrderStatusEnum.PAID_OFF.name())){

            OrderDO orderDO = orderMessage.getOrderDO();
            PayLog payLog = this.payLogManager.getModel(orderDO.getSn());

            // 查询支付方式
            PaymentMethodDO paymentMethod = this.paymentMethodManager.getByPluginId(orderDO.getPaymentPluginId());
            if( paymentMethod == null ){
                paymentMethod = new PaymentMethodDO();
                paymentMethod.setMethodName("管理员确认收款");
            }

            payLog.setPayType(paymentMethod.getMethodName());
            payLog.setPayTime(orderDO.getPaymentTime());
            payLog.setPayMoney(orderDO.getPayMoney());
            payLog.setPayStatus(PayStatusEnum.PAY_YES.name());
            payLog.setPayOrderNo(orderDO.getPayOrderNo());

            this.payLogManager.edit(payLog,payLog.getPayLogId());

            if (paymentMethod.getPluginId().equals(PaymentPluginEnum.mergePayPlugin.name())) {
                List<PaymentBillDO> paymentBillList = paymentBillManager.getBillListBySnAndTradeType(orderDO.getSn(), orderDO.getTradeType());
                if (!CollectionUtils.isEmpty(paymentBillList)) {
                    PayLog newPayLog = new PayLog();
                    for (PaymentBillDO paymentBill : paymentBillList) {
                        newPayLog.setOrderSn(orderDO.getSn());
                        newPayLog.setPayLogSn(tradeSnCreator.generatePayLogSn());
                        newPayLog.setPayMemberName(orderDO.getMemberName());
                        newPayLog.setPayWay(orderDO.getPaymentType());
                        newPayLog.setPayType(paymentBill.getPaymentName());
                        newPayLog.setPayTime(orderDO.getPaymentTime());
                        newPayLog.setPayMoney(paymentBill.getTradePrice());
                        newPayLog.setPayStatus(PayStatusEnum.PAY_YES.name());
                        newPayLog.setPayOrderNo(paymentBill.getReturnTradeNo());

                        this.payLogManager.add(newPayLog);
                    }
                }
            }

            // 如果没有上线就先关闭下面功能 解决虚拟账户和原结算数据一致性问题
            if(!SettleUtils.isGoOnline(orderDO.getCreateTime())){
                logger.info("钱包结算功能暂未开启");
                return;
            }

            // by sunjian 付款更新账户金额
            String paymentMethodName = orderDO.getPaymentMethodName();
            if(StringUtils.isBlank(paymentMethodName)){
                logger.error("此订单(" + orderDO.getSn() + ")没有支付方式，但是状态为已付款");
                return;
            }

            if(paymentMethodName.equals(AccountTypeEnum.WALLETPAY.description())){
                logger.debug("此订单(" + orderDO.getSn() + ")为钱包支付，已生成过支付记录");
                return;
            }

            // 查询订单
            Integer memberId = orderDO.getMemberId();
            Member member = memberManager.getModel(memberId);
            String accountMemberId = member.getAccountMemberId();

            PaymentRecordDTO paymentRecordDTO = new PaymentRecordDTO();
            paymentRecordDTO.setTradeVoucherNo(payLog.getOrderSn());
            paymentRecordDTO.setDraweeMemberId(accountMemberId);
            paymentRecordDTO.setAmount(BigDecimal.valueOf(orderDO.getPayMoney()));
            paymentRecordDTO.setTradeSubject(TradeSubjectEnum.ORDER_PAYMENT_WEIXIN.description());
            paymentRecordDTO.setTradeContent("订单号" + orderDO.getSn() + "交易款项");

            if(paymentMethodName.equals(AccountTypeEnum.ALIPAY.description())){
                paymentRecordDTO.setTradeChannel(TradeChannelEnum.ALIPAY.getIndex());
            } else if (paymentMethodName.equals(AccountTypeEnum.WEIXINPAY.description())){
                paymentRecordDTO.setTradeChannel(TradeChannelEnum.WECHAT.getIndex());
            } else if (paymentMethodName.equals(AccountTypeEnum.MERGEPAY.description())) {
                paymentRecordDTO.setAmount(BigDecimal.valueOf(CurrencyUtil.sub(orderDO.getPayMoney(), orderDO.getWalletPayPrice())));
                paymentRecordDTO.setTradeChannel(TradeChannelEnum.WECHAT.getIndex());
            } else {
                logger.error("此订单(" + orderDO.getSn() + ")支付方式为" + paymentMethodName + ",无法生成支付记录");
                return;
            }

            paymentRecordDTO.setTradeStatus(TradeStatusEnum.TRADE_STATUS_SUCCESS.getIndex());
            paymentRecordDTO.setTradeTime(new Date(orderDO.getPaymentTime() * 1000));
            paymentRecordDTO.setOperatorId(accountMemberId);
            paymentRecordDTO.setOperatorName(member.getNickname());
            accountManager.paymentRecord(paymentRecordDTO);
        }

    }


}
